package com.leyou.page.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpuDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class PageService {

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private SpringTemplateEngine templateEngine;

    @Value("${ly.static.itemDir}")
    private String itemDir;

    @Value("${ly.static.itemTemplate}")
    private String itemTemplate;

    public Map<String, Object> loadItemPage(Long id) {
        Map<String, Object> data = new HashMap<>();
        //查询spu
        SpuDTO spuDTO = itemClient.querySpuById(id);
        //查询分类
        List<CategoryDTO> categoryDTOS = itemClient.queryCategoryByIds(spuDTO.getCategoryIds());
        //查询品牌
        BrandDTO brandDTO = itemClient.queryBrandId(spuDTO.getBrandId());
        //查询规格组
        List<SpecGroupDTO> specGroupDTOS = itemClient.querySpecsByCid(spuDTO.getCid3());

        data.put("categories",categoryDTOS);    // 根据id查询分类
        data.put("brand",brandDTO);         // 根据id查询品牌
        data.put("spuName",spuDTO.getName());       // 来自于SpuDTO
        data.put("subTitle",spuDTO.getSubTitle());      // 来自于SpuDTO
        data.put("detail",spuDTO.getSpuDetail());        // 根据id查询详情
        data.put("skus",spuDTO.getSkus());          // SpuDetail对象
        data.put("specs",specGroupDTOS);         // 规格组集合，每个规格组中有个规格参数的集合
        return data;
    }

    public void createItemHtml(Long id){
        Context context = new Context();
        context.setVariables(loadItemPage(id));
        File dir = new File(itemDir);
        if(!dir.exists()){
            if(!dir.mkdirs()){
                log.error("【静态页服务】创建静态页目录失败，目录地址：{}", dir.getAbsolutePath());
                throw new LyException(ExceptionEnum.DIRECTORY_WRITER_ERROR);
            }
        }
        File filePath = new File(dir, id + ".html");
        try(PrintWriter writer = new PrintWriter(filePath,"UTF-8")){
            templateEngine.process(itemTemplate,context,writer);
        }catch (IOException e){
            log.error("【静态页服务】静态页生成失败，商品id：{}", id, e);
            throw new LyException(ExceptionEnum.FILE_WRITER_ERROR);
        }
    }

    public void deleteItemHtml(Long spuId) {
        File file = new File(itemDir, spuId + ".html");
        if(file.exists()){
            boolean delete = file.delete();
            if(!delete){
                log.error("【静态页服务】静态页删除失败，商品id：{}", spuId);
                throw new LyException(ExceptionEnum.DELETE_OPERATION_FAIL);
            }
        }
    }
}
